<template>
  <div class="token-status">
    <a-dropdown :trigger="['click']" placement="bottomRight">
      <a-button type="text" size="small" :loading="loading">
        <template #icon>
          <ClockCircleOutlined />
        </template>
        {{ statusText }}
      </a-button>

      <template #overlay>
        <a-menu class="w-64">
          <a-menu-item disabled>
            <div class="p-2">
              <div class="text-xs text-gray-500 mb-1">Token状态</div>
              <div class="flex items-center justify-between">
                <span class="text-sm">剩余时间:</span>
                <span class="text-sm font-medium" :class="getTimeColor()">
                  {{ tokenInfo?.remainingTimeText || '未知' }}
                </span>
              </div>
              <div class="flex items-center justify-between mt-1">
                <span class="text-sm">过期时间:</span>
                <span class="text-xs text-gray-500">
                  {{ formatExpirationTime() }}
                </span>
              </div>
            </div>
          </a-menu-item>

          <a-menu-divider />

          <a-menu-item @click="handleRefreshToken" :disabled="refreshing">
            <template #icon>
              <ReloadOutlined :spin="refreshing" />
            </template>
            手动续期
          </a-menu-item>

          <a-menu-item @click="handleCheckStatus" :disabled="checking">
            <template #icon>
              <SyncOutlined :spin="checking" />
            </template>
            检查状态
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import {
  ClockCircleOutlined,
  ReloadOutlined,
  SyncOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

import type { AuthApi } from '#/api/core/auth';
import { useAuthStore } from '#/store/auth';
import { useAutoTokenManager } from '#/hooks/useAutoTokenManager';

const authStore = useAuthStore();

// 获取动态配置
const { renewalThresholdMinutes } = useAutoTokenManager();

const loading = ref(false);
const refreshing = ref(false);
const checking = ref(false);
const tokenInfo = ref<AuthApi.TokenStatusResult | null>(null);
const updateTimer = ref<number | null>(null);

// 状态文本
const statusText = computed(() => {
  if (!tokenInfo.value) return 'Token';

  const remainingMs = tokenInfo.value.remainingTimeMs;
  const criticalThreshold = Math.min(renewalThresholdMinutes.value / 2, 5) * 60 * 1000;
  const warningThreshold = renewalThresholdMinutes.value * 60 * 1000;

  if (remainingMs < criticalThreshold) {
    return '即将过期';
  } else if (remainingMs < warningThreshold) {
    return '需要续期';
  } else {
    return 'Token正常';
  }
});

// 获取时间颜色
const getTimeColor = () => {
  if (!tokenInfo.value) return 'text-gray-500';

  const remainingMs = tokenInfo.value.remainingTimeMs;
  const criticalThreshold = Math.min(renewalThresholdMinutes.value / 2, 5) * 60 * 1000;
  const warningThreshold = renewalThresholdMinutes.value * 60 * 1000;

  if (remainingMs < criticalThreshold) {
    return 'text-red-500';
  } else if (remainingMs < warningThreshold) {
    return 'text-orange-500';
  } else {
    return 'text-green-500';
  }
};

// 格式化过期时间
const formatExpirationTime = () => {
  if (!tokenInfo.value?.expirationTime) return '未知';

  const date = new Date(tokenInfo.value.expirationTime);
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

// 更新Token状态
const updateTokenStatus = async () => {
  try {
    loading.value = true;
    tokenInfo.value = await authStore.getTokenInfo();
  } catch (error) {
    console.error('获取Token状态失败:', error);
  } finally {
    loading.value = false;
  }
};

// 手动刷新Token
const handleRefreshToken = async () => {
  try {
    refreshing.value = true;
    const success = await authStore.refreshToken();
    if (success) {
      await updateTokenStatus();
    }
  } finally {
    refreshing.value = false;
  }
};

// 检查Token状态
const handleCheckStatus = async () => {
  try {
    checking.value = true;
    await updateTokenStatus();
    console.log('Token状态已更新');
  } finally {
    checking.value = false;
  }
};

// 开始定时更新（仅更新状态，不进行自动续期）
const startPeriodicUpdate = () => {
  stopPeriodicUpdate();
  updateTimer.value = window.setInterval(updateTokenStatus, 30 * 1000); // 30秒更新一次
};

// 停止定时更新
const stopPeriodicUpdate = () => {
  if (updateTimer.value) {
    clearInterval(updateTimer.value);
    updateTimer.value = null;
  }
};

onMounted(() => {
  updateTokenStatus();
  startPeriodicUpdate();
});

onUnmounted(() => {
  stopPeriodicUpdate();
});
</script>

<style scoped>
.token-status {
  /* 可以添加自定义样式 */
}
</style>
